package com.basic.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolTest {

	public static void main(String[] args) {
		ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(1);
		ThreadPoolExecutor executor = new ThreadPoolExecutor(1,
				2, 
				2, 
				TimeUnit.SECONDS, 
				workQueue, 
				new TestThreadFactory(), 
				new PrintRejectedExecutionHandler());
		for (int i = 1; i <= 3; i++) {
			if (i==3) {
				//executor.shutdown();
				//executor.shutdownNow();
			}
			executor.execute(new WorkerTask(i));
		}
		try {
			Thread.sleep(1000*1);
			System.out.println("执行时线程数： "+ executor.getPoolSize());
			Thread.sleep(1000*10);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("执行结束后线程数： "+ executor.getPoolSize());
		executor.shutdown();
		executor.shutdownNow();
//		try {
//			executor.awaitTermination(1, TimeUnit.SECONDS);
//			
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
	}
	
	public static class WorkerTask implements Runnable{
		
		private final int taskNum;
		
		public WorkerTask(int taskNum){
			this.taskNum = taskNum;
		}
		
		public int getTaskNum() {
			return taskNum;
		}
		
		public void run() {
			try {
				System.out.println("线程： "+ Thread.currentThread().getName()+" 任务编号："+taskNum+" 正在执行任务......");
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("线程： "+ Thread.currentThread().getName()+" 任务编号："+taskNum+" 任务执行完成......");
		}
	}
	
	public static class TestThreadFactory implements ThreadFactory{
		
		private static final AtomicInteger ThreadNum = new AtomicInteger();
		
		public Thread newThread(Runnable r) {
			Thread thread = new Thread(r);
			thread.setName("TEST-POOL-"+ThreadNum.incrementAndGet());
			return thread;
		}
	}
	
	public static class PrintRejectedExecutionHandler implements RejectedExecutionHandler{
		
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			System.out.println("任务被拒绝： "+ ((WorkerTask)r).getTaskNum());
			//重新加入到队列中进行执行。
			try {
				executor.getQueue().put(r);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
